% TaiTfm
% Christopher J. Whalen
% University of Illinois
% 06/28/04

% Purpose - this program takes a Nx3 matrix of coordinates and transforms
%           them into Talairach space using the Talairach marker coordinates

function [xyz] = TaiTfm(tai, xyz)

fprintf('Talairach Transforming File...\n');

% origin (AC), Post Commisure, front, back, top, bottom, left, right ? [LPI] ?
%
tai_ref = [0 0 0; 0 -23 0; 0 70 0; 0 -102 0; 0 0 74; 0 0 -42; -68 0 0; 68 0 0]; 

for i=1:length(xyz)
    sx = sign(xyz(i,1));
    sy1 = sign(xyz(i,2));
    sy2 = sign(xyz(i,2)+23); % if sy1 and sy2 are neg then they are most posterior
    sz = sign(xyz(i,3));
    % X transform
    if sx > 0
        xyz(i,1) = xyz(i,1)*tai_ref(8,1)/tai.xyz(8,1);
    elseif sx < 0
        xyz(i,1) = xyz(i,1)*tai_ref(7,1)/tai.xyz(7,1);
    elseif sx == 0
        xyz(i,1) = xyz(i,1);
    end
    % Y transformation
    if sy1 > 0
        xyz(i,2) = xyz(i,2)*tai_ref(3,2)/tai.xyz(3,2);
    elseif (sy1 < 0) & (sy2 >= 0)
        xyz(i,2) = xyz(i,2)*tai_ref(2,2)/tai.xyz(2,2);
    elseif (sy1 < 0) & (sy2 < 0)
        xyz(i,2) = tai_ref(2,2) + ((xyz(i,2)-tai.xyz(2,2))*(tai_ref(4,2)-tai_ref(2,2))/(tai.xyz(4,2)-tai.xyz(2,2)));
    elseif sy1 == 0
        xyz(i,2) = xyz(i,2);
    end
    % Z transformation
    if sz > 0
        xyz(i,3) = xyz(i,3)*tai_ref(5,3)/tai.xyz(5,3);
    elseif sz < 0
        xyz(i,3) = xyz(i,3)*tai_ref(6,3)/tai.xyz(6,3);
    elseif sz == 0
        xyz(i,3) = xyz(i,3);
    end
end



